import { MongoClient } from "mongodb";

const MONGODB_URI =
  process.env.MONGODB_URI || "mongodb://localhost:27017/login-system";

let client;
let db;

export const connectDB = async () => {
  try {
    if (!client) {
      client = new MongoClient(MONGODB_URI);
      await client.connect();
      db = client.db();
      console.log("✅ MongoDB 连接成功");

      // 创建索引
      await createIndexes();
    }
    return db;
  } catch (error) {
    console.error("❌ MongoDB 连接失败:", error);
    process.exit(1);
  }
};

export const getDb = () => {
  if (!db) {
    throw new Error("数据库未连接");
  }
  return db;
};

const createIndexes = async () => {
  try {
    const users = db.collection("users");

    // 创建用户名唯一索引
    await users.createIndex({ username: 1 }, { unique: true });
    console.log("✅ 用户名索引创建成功");

    // 创建邮箱唯一索引
    await users.createIndex({ email: 1 }, { unique: true });
    console.log("✅ 邮箱索引创建成功");
  } catch (error) {
    console.error("❌ 索引创建失败:", error);
  }
};

// 优雅关闭
process.on("SIGINT", async () => {
  if (client) {
    await client.close();
    console.log("📴 数据库连接已关闭");
  }
  process.exit(0);
});
